package org.csu.mypetstore.controller;

import org.springframework.ui.Model;
import jakarta.servlet.http.HttpSession;
import org.csu.mypetstore.domain.Order;
import org.csu.mypetstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("shipping")
public class ShippingController {

    @Autowired
    private OrderService orderService;

    // 显示配送地址表单
    @GetMapping
    public String shippingForm(HttpSession session, Model model) {
        // 从session获取原始订单
        Order originalOrder = (Order) session.getAttribute("order");
        if (originalOrder == null) {
            return "redirect:/cart/view";
        }
        model.addAttribute("order", originalOrder);
        return "order/ShippingForm";
    }

    // 更新配送地址
    @PostMapping
    public String updateShipping(
            @ModelAttribute Order newShipping,
            HttpSession session,
            RedirectAttributes redirectAttributes) {

        // 获取原始订单
        Order originalOrder = (Order) session.getAttribute("order");
        if (originalOrder == null) {
            redirectAttributes.addFlashAttribute("error", "会话已过期");
            return "redirect:/cart/view";
        }

        // 更新配送地址
        orderService.updateShippingAddress(originalOrder, newShipping);

        // 更新session中的订单
        session.setAttribute("order", originalOrder);

        return "redirect:/order/new";
    }



    /*
    @GetMapping
    public String shippingForm(@ModelAttribute Order order) {
        return "order/ShippingForm";
    }





    @PostMapping
    public String updateShipping(
            @ModelAttribute Order order,
            @SessionAttribute("originalOrder") Order originalOrder) {

        orderService.updateShippingAddress(originalOrder, order);
        return "redirect:/order/new";
    }
     */
}
